package org.ossr.portlets.pm.portlets;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletSecurityException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.ossr.portlets.pm.service.PrivateMessageLocalServiceUtil;

import sun.net.util.URLUtil;

import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ThemeLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class PrivateMessagePortlet
 */
public class PrivateMessagePortlet extends MVCPortlet {
	
	@Override
	public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {		
		// TODO Auto-generated method stub

		super.doView(renderRequest, renderResponse);		
	}
 	
	public void composeMessage(ActionRequest request, ActionResponse response) throws Exception {
		ThemeDisplay td = (ThemeDisplay) request.getAttribute("THEME_DISPLAY");
		
		Set<User> list = new HashSet<User>();
		
		User currentUser = UserLocalServiceUtil.getUser(td.getUserId());

		long[] groupsIds = currentUser.getGroupIds();
		
		for(long groupId : groupsIds ){
			for(User user : UserLocalServiceUtil.getGroupUsers(groupId)){
				if ( !list.contains(user) && user.getUserId() != td.getUserId()){
					list.add(user);
				}
			}
		}
		
		List<Group> groups = currentUser.getGroups(); 
		
		request.setAttribute("availableUsers", list);
		request.setAttribute("availableGroups", groups);
		
		response.setRenderParameter("jspPage", "/html/pm/compose.jsp");		
	}
	
	public void sendMessage(ActionRequest request, ActionResponse response) throws Exception{
		String fromAction = ParamUtil.getString(request, "fromAction");
		if ( fromAction.equalsIgnoreCase("cancel")){
			response.setProperty("fromAction", "cancel");
		}
		response.setRenderParameter("jspPage", "/html/pm/view.jsp");	
	}

}
